package com.xr.singleton.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xr.singleton.model.entity.ResourceEntity;
import com.xr.singleton.model.entity.UserEntity;
import com.xr.singleton.mapper.*;
import com.xr.singleton.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by BlueT on 2018/3/3.
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;


    @Override
    public List<UserEntity> list(Map<String, Object> params) {
        List<UserEntity> userEntities = userMapper.selectList(new QueryWrapper<>());
        return userEntities;
    }

    @Override
    public IPage<UserEntity> listByPage(Integer pageNum, Integer pageSize) {
        Page<UserEntity> page = new Page<>(pageNum, pageSize);
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        return userMapper.selectPage(page, queryWrapper);
    }

    @Override
    public UserEntity getInfoById(Long id) {
        UserEntity userEntity = userMapper.selectById(id);
        List<ResourceEntity> resourceEntities = resourceMapper.listByUserId(id);

        List<Map<String, Object>> oList = new ArrayList<>(resourceEntities.size());
        for (ResourceEntity resourceEntity : resourceEntities){
            Map<String, Object> oMap = new HashMap<>(2);
            oMap.put("path", resourceEntity.getPath());
            oMap.put("permission", resourceEntity.getPermission());
            oList.add(oMap);
        }
        userEntity.setPermissions(oList);
        return userEntity;
    }
}
